import {
  list, detail, update, create, queryData, basicInfo, remove,
  metaTypes, copyPath, updateIndex,
} from '../services/index';
import { detail as appDetail } from '../services/app';
import { stateCreate, effectsCreate, reducers, dataHandle } from 'src/models/modelCreator';
import { systemConstants } from 'src/utils/constants';
import { transform, tools } from 'src/utils';
import { message } from 'antd';

export default {
    namespace: 'index',
    state: {
      ...stateCreate(),
      moduleName: 'index',
      entityDescription: '索引',
      relatedData: {
        appData: {},
        metaTypes: [],
        copyPath: {
          suggestion: 'suggestion',
          default_search_field: 'default_search_field',
        }
      },
      showQueryModal: false,
      dataQueryType: 'sql',
      dataQueryResult: {
          generalInfo: '',
          columns: [],
          list: []
      },
      entity: {
        basicInfo: {
          id: null
        },
        fields: []
      }
    },
    effects: {
      ...effectsCreate({ list, detail, update, create, remove }, dataHandle),

      * updateIndex ({ payload, }, { call, put }) {
        const { data, error } = yield call(updateIndex, payload);

        if (!error) {
          yield put({
            type: 'closeDetailModal'
          });
          yield put({
            type: 'list',
            payload: { module: 'index' }
          });
        }
        else {
          message.error(error.toString());
        }
      },

      * readBasic({ payload, }, { call, put, select }) {
          const { data, error } = yield call(basicInfo, payload);
          yield dataHandle.detailHandle({ data: { basicInfo: data }, error }, { put });
      },

      * relatedData({ payload, }, { call, put, select }) {
        const {projectId} = yield select(state => state[payload.module]['searchParams']);

        const appDetailReq = call(appDetail, projectId);
        const metaTypesReq = call(metaTypes);


        const appResp = yield appDetailReq;
        const metaTypesResp = yield metaTypesReq;

        const { data, error } = {
          data: { appData: appResp.data, metaTypes: metaTypesResp.data },
          error: appResp.error || metaTypes.error
        };
        yield dataHandle.relatedDataHandle({ data, error }, { put });
      },

      * startShowQuery({ payload, }, { call, put, select }) {
        const { data, error } = yield call(basicInfo, payload);
        yield dataHandle.detailHandle({ data: { basicInfo: data }, error }, { put });

        yield put({
          type: 'showQuery',
          payload: payload,
        });
      },

      * handleQuerySubmit({ payload, }, { call, put, select }) {
        const dataQueryType = yield select(state => state[payload.module]['dataQueryType']);
        const indexName = yield select(state => state[payload.module]['entity']['basicInfo']['indexName']);
        const searchParams = { ...payload[dataQueryType], type: dataQueryType, indexName };
        const { data, error } = yield call(queryData, searchParams);
        if (data) {
          yield put({
            type: 'querySuccess',
            payload: data
          });
        } else if (error && error.fieldErrors) {
          yield put({
            type: 'putError',
            payload: {
              fieldErrors: error.fieldErrors,
            }
          });
        }
      },
    },
    subscriptions: {
      setup({ history, dispatch }) {
        // 监听 history 变化，当进入 `/` 时触发 `load` action
        return history.listen(({ pathname, query }) => {
          dispatch({
            type: 'paramsChange',
            payload: query
          });

          if (pathname.match(/\/index/)) {
            dispatch({
              type: 'list',
              payload: { module: 'index' }
            });

            dispatch({
              type: 'relatedData',
              payload: { module: 'index' }
            });
          }
        });
      },
    },
    reducers: {
      ...reducers,
      relatedDataSuccess(state, action) {
        const {appData, metaTypes } = action.payload;
        return {
          ...state,
          relatedData: {
            ...state.relatedData,
            appData,
            metaTypes
          },
        };
      },

      loadDetailSuccess(state, action) {
        let newEntity = { basicInfo: action.payload.basicInfo };
        if (action.payload.fields) {
          newEntity.fields = transform.addKey(action.payload.fields);
        }
        return {
          ...state,
          entity: {
            ...state.entity,
            ...newEntity,
          }
        }
      },

      showQueryModal(state, action) {
        return {
          ...state,
          showQueryModal: true,
        };
      },

      closeQueryModal(state, action) {
        return {
          ...state,
          showQueryModal: false,
        };
      },

      onDataQueryTypeChange(state, action) {
        return {
          ...state,
          dataQueryType: action.payload,
        };
      },

      querySuccess(state, action) {
        const columns = action.payload.resultColumns.map(
          (item, index) => ({
            title: item,
            dataIndex: item,
            key: item,
          }),
        );
        const list = action.payload.result.map(
          (item, index) => ({
            ...item,
            key: index + new Date().getTime()
          }),
        );

        const generalInfo = '查到数据' + list.length + '条，耗时' + action.payload.time + 'ms';

        return {
          ...state,
          dataQueryResult: {
            list,
            columns,
            generalInfo
          }
        };
      },

      closeDetailModal(state) {
        return {
          ...state,
          entity: {
            basicInfo: {
              id: null
            },
            fields: []
          },
          showDetailModal: false
        }
      },
    }
}
